import React, { useState, useEffect, useRef, ElementRef } from 'react';
import { useSearchParams } from 'react-router-dom';
import M from '@block/utils';
import { Container, Button, notification, Tooltip } from '@block/plug';
import { Tabs } from '@ss/mtd-react';
import { MenuCode, LimitsAuthority } from '@src/utils';
import { RuleManageRecords, RuleDetailDrawer } from './elements/index';
import { TabStatus, TabCode, TabCountData } from './type';
import URL from './url';
import './index.scss';

const { Header, Main } = Container;

/**
 * 规则管理菜单
 */
const RuleManage = () => {
  /** queryString 参数声明 */
  const [searchParams, setSearchParams] = useSearchParams();

  /** state 定义 */
  const [tabCountData, setTabCountData] = useState<TabCountData>(); // tab角标数字
  const [activeTab, setActiveTab] = useState<TabCode>('All'); // 当前激活tab
  const [detailDrawerVisible, setDetailDrawerVisible] = useState<boolean>(false); // 规则详情侧滑展示状态
  const [queryStringRuleId, setQueryStringRuleId] = useState<number>(null); // url上queryString的ruleId
  const [pageActions, setPageActions] = useState<Array<LimitsAuthority>>([]); // 页面操作权限

  /** ref 定义 */
  const ruleManageRecordsRef = useRef<ElementRef<typeof RuleManageRecords>>(null); // 新建表单form实例

  // tabs配置信息
  const tabsConfig = [
    { key: 'All', name: '全部', count: tabCountData?.allStatusCount },
    { key: 'NeedSubmit', name: '待提交', count: tabCountData?.needSubmitStatusCount },
    { key: 'Audit', name: '审批中', count: tabCountData?.auditStatusCount },
    { key: 'Valid', name: '生效中', count: tabCountData?.validStatusCount },
    { key: 'Invalid', name: '已失效', count: tabCountData?.invalidStatusCount },
  ];

  /** 获取各状态下数据量 */
  const getStatusCount = async () => {
    const res = await M.$fetch<TabCountData>(URL.countByStatus, {});
    setTabCountData(res);
  };

  /** 获取页面初始化数据 */
  const getInitData = async () => {
    const ruleId = searchParams.get('ruleId');
    if (ruleId) {
      setQueryStringRuleId(+ruleId);
      setDetailDrawerVisible(true);
    }
    const res = await M.$fetch<Array<LimitsAuthority>>(URL.queryPermissionListByMenu, {
      menuCode: MenuCode.senPosRuleManage,
    });
    setPageActions(res || []);
  };

  /** DidMount */
  useEffect(() => {
    getStatusCount();
    getInitData();
  }, []);

  /** 导出处理 */
  const handleExport = async () => {
    const params = ruleManageRecordsRef.current?.getFilterValue();
    const res = await M.$fetch<OperateResponse>(URL.exportRule, params);
    notification.success({ title: '成功', message: res.message || '操作成功' });
  };

  return (
    <div className="rule-manage">
      <Header className="rule-manage-header" style={{ height: 'auto' }}>
        <div className="header-title">
          <span>规则管理</span>
        </div>
        <div className="header-btns">
          {['All', 'Valid'].includes(activeTab) && pageActions.includes(LimitsAuthority.export) && (
            <Tooltip message="导出查询结果全部数据" autoDestory>
              <Button onClick={handleExport} rightIcon="info-circle-o" type="normal">
                导出
              </Button>
            </Tooltip>
          )}
          {['All', 'NeedSubmit', 'Valid'].includes(activeTab) && pageActions.includes(LimitsAuthority.add) && (
            <Button onClick={() => setDetailDrawerVisible(true)} type="primary">
              新建
            </Button>
          )}
        </div>
      </Header>
      <Main className="rule-manage-main">
        <Tabs
          autoDestory
          activeKey={activeTab}
          onChange={(activeKey: TabCode) => {
            getStatusCount();
            setActiveTab(activeKey);
          }}
        >
          {tabsConfig.map((tab) => {
            return (
              <Tabs.TabPane
                key={tab.key}
                label={
                  <span>
                    <span>{tab.name}</span>
                    {!!tab.count && <span>({tab.count})</span>}
                  </span>
                }
              >
                <RuleManageRecords
                  ref={ruleManageRecordsRef}
                  tabStatus={TabStatus[tab.key]}
                  pageActions={pageActions}
                  getStatusCount={getStatusCount}
                />
              </Tabs.TabPane>
            );
          })}
        </Tabs>
      </Main>
      {detailDrawerVisible && (
        <RuleDetailDrawer
          drawerMode={queryStringRuleId ? 'view' : 'create'}
          setDetailDrawerVisible={setDetailDrawerVisible}
          getStatusCount={getStatusCount}
          recordsSearch={ruleManageRecordsRef.current?.recordsSearch}
          ruleId={queryStringRuleId}
          setSearchParams={setSearchParams}
        />
      )}
    </div>
  );
};

export default RuleManage;
